package com.example.actordemo3.total;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.OnSuccess;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.example.actordemo3.cluster.ClusterActor;
import com.typesafe.config.ConfigFactory;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class StartFrontend {

    public static void main(String[] args) {


        ActorSystem system = ActorSystem.create("sys",
                ConfigFactory.load("cluster4.conf"));
        ActorRef actorRef = system.actorOf(Props.create(WordFrontService.class), "wordFrontService");

        String result = "";
        while (true){
            Future<Object> fu = Patterns.ask(actorRef, "isready", 1000);
            try {
                result = (String) Await.result(fu, Duration.create(1000, TimeUnit.SECONDS));
            } catch (Exception e) {
                e.printStackTrace();
            }

            if(result.equals("ready")){
                System.out.println("================= ready======");
                break;
            }
        }

        List<Article> articles = new ArrayList<>();
        for (int i=0;i<3;i++){
            Article article = new Article();
            article.setId("文章"+i);
            double random = Math.random()*1000;

            article.setContent("11111ssss"+random);
            articles.add(article);
        }

        Timeout timeout = new Timeout(Duration.create(3,TimeUnit.SECONDS));
        for (Article article : articles) {
            Patterns.ask(actorRef,article,timeout).onSuccess(new OnSuccess<Object>() {
                @Override
                public void onSuccess(Object result) throws Throwable {
                   CountResult countResult = (CountResult)result;
                    System.out.println("文件"+ countResult.getId()+"数量"+countResult.getCount());
                }
            },system.dispatcher());
        }


    }
}
